var gamejs = require('gamejs');
var mainTurret = require('js/turret');
var Projectile = require('js/turrets/projectile').Projectile;
/**
 * Create a Turret object
 *
 * @param {Match} match The match where this object will work
 * @param {[number, number]} coords The radar's position, in format [x, y]
 */
var GunTurret = exports.GunTurret = function(match, coordinates, tf) {
	GunTurret.superConstructor.call(this , match, coordinates, tf);

	// The time (in ms) to wait before shooting again
	this._reloading = 0;

	// Coordinates of the Turret weapon location (for a better animation)
	this._weaponCoordinates = [
		this.rect.center[0] - 17,
		this.rect.center[1] - 3
	];
};

/**
 * The list of available upgrades
 */
GunTurret.UPGRADE_LIST = [
	// Level 0
	{price: 80, range: 100, reloadTime: 1000, resaleValue: 40,
		image: IMAGE_ROOT + "turrets/gunturret.png", projectilePower: 1
	},
	// Level 1
	{price: 60, range: 150, reloadTime: 500, resaleValue: 70,
		image: IMAGE_ROOT + "turrets/gunturret1.png", projectilePower: 2
	}
];

gamejs.utils.objects.extend(GunTurret, mainTurret.Turret);

/**
 * Returns the delay between a shoot and the next one
 *
 * @return {number} The shooting delay (in milliseconds)
 */
GunTurret.prototype.getReloadTime = function() {
	return this.getLevelSettings().reloadTime;
};

/**
 * Returns the turret's projectiles power
 *
 * @return {number}
 */
GunTurret.prototype.getProjectilePower = function() {
	return this.getLevelSettings().projectilePower;
};

/**
 * Return the coordinates of the weapon
 *
 * @return {[Number, Number]} The [x, y] coordinates of the turret weapon
 */
GunTurret.prototype.getWeaponCoordinates = function() {
	return this._weaponCoordinates;
};

/**
 * Updates the turret status by detecting if it has to shoot or the shooting
 * ray position if already shooting
 *
 * @param {number} msDuration The time past from the last call (in ms)
 */
GunTurret.prototype.update = function(msDuration) {
	// If turret is still reloading update _reloading
	if (this._reloading - msDuration > 0) {
		this._reloading = this._reloading - msDuration;
	}
	// else Turret can shoot
	else {
		// If a target is available shoot it down
		var target = this._targetEnemy();
		if (target) {
			this.getMatchMap().addProjectile(
				new Projectile(target, this, this.getProjectilePower())
			);
			// Now the turret needs to reload
			this._reloading = this.getReloadTime();
		}
		// if there isn't a target keep the turret ready to shoot
		else {
			this._reloading = 0;
		}
	}
};

